<?php
declare (strict_types = 1);

namespace app\model\concern;

use app\model\communal\AdminModel;
use think\db\Query;
use think\model\relation\BelongsTo;

trait AmisTrait
{
    /**
     * 状态搜索
     *
     * @param Query $query
     * @param $value
     */
    public function searchStateAttr($query, $value)
    {
        if (!empty($value)) {
            $query->where('state', $value);
        }
    }

    /**
     * admin_id搜索
     *
     * @param Query $query
     * @param $value
     */
    public function searchAdminIdAttr($query, $value)
    {
        if (!empty($value)) {
            $query->where('admin_id', $value);
        }
    }

    /**
     * createtime 时间范围搜索
     *
     * @param Query $query
     * @param $value
     */
    public function searchCreatetimeAttr($query, $value)
    {
        if (!empty($value)) {
            $range = explode(',', $value);
            $start = $range[0];
            $end = $range[1];
            $query->where('created_at', '>=', $start);
            $query->where('created_at', '<=', $end);
        }
    }

    /**
     * amis城市修改
     *
     * @param $value
     * @return mixed
     */
    public function setAmisCityAttr($value)
    {
        if (!empty($value)) {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }

        return $value;
    }

    /**
     * 关联创建人
     *
     * @return BelongsTo
     */
    public function byCreator()
    {
        return $this->belongsTo(AdminModel::class, 'admin_id', 'id')
            ->removeOption('soft_delete')
            ->bind(['creator' => 'name']);
    }
}
